package org.clockworkmages.games.anno1186.text;

import java.util.ArrayList;
import java.util.List;

class ComplexTextNode implements TextNode {

	private List<TextNode> children = new ArrayList<TextNode>();

	public ComplexTextNode(String text) {

		String remainingText = text == null ? "" : text;

		while (remainingText.length() > 0) {
			int openingIndex = remainingText.indexOf("${");
			int closingIndex = remainingText.indexOf("}");

			if (openingIndex > closingIndex) {
				// TODO report error
				break;
			}

			if (openingIndex > -1) {
				if (closingIndex < openingIndex) {
					// TODO report error
					break;
				}
				children.add(new PlainTextNode(remainingText.substring(0,
						openingIndex)));
			} else {
				children.add(new PlainTextNode(remainingText));
				break;
			}

			String expression = remainingText.substring(openingIndex + 2,
					closingIndex);
			if (expression.startsWith("if ")) {
				// //TODO
				int matchingClosingExpressionIndex = 0;
				String remainingText2 = remainingText.substring(openingIndex);
				int ifCount = 0; // counts additional "if" clauses that may be
									// embedded inside the main "if" condition
				while (true) {
					int firstIfIndex = remainingText2.indexOf("${if ");
					int firstFiIndex = remainingText2.indexOf("${fi}");

					if (firstFiIndex == -1) {
						throw new RuntimeException(
								"Text contains invalid conditional expressions and cannot be parsed: "
										+ text);
					} else if (firstFiIndex < firstIfIndex
							|| firstIfIndex == -1) {
						if (ifCount == 1) {
							matchingClosingExpressionIndex += firstFiIndex;
							break;
						} else {
							ifCount--;
						}
						matchingClosingExpressionIndex += firstFiIndex + 2;
						remainingText2 = remainingText2
								.substring(firstFiIndex + 2);
					} else {
						ifCount++;
						matchingClosingExpressionIndex += firstIfIndex + 2;
						remainingText2 = remainingText2
								.substring(firstIfIndex + 2);
					}
				}
				String ifExpression = remainingText.substring(openingIndex,
						openingIndex + matchingClosingExpressionIndex + 5);
				children.add(new ConditionalTextNode(ifExpression));
				remainingText = remainingText.substring(openingIndex
						+ matchingClosingExpressionIndex + 5);

			} else {
				children.add(new PlaceholderTextNode(expression));
				remainingText = remainingText.substring(closingIndex + 1);
			}
		}
	}

	@Override
	public String getParsedText() {
		StringBuffer sb = new StringBuffer();
		for (TextNode textNode : children) {
			sb.append(textNode.getParsedText());
		}
		return sb.toString();
	}

}